package com.tech.pattern.singleton;

/**
 * @Description: 恶汉式单例
 * @Author: zl
 * @Date: 2019/9/11 23:22
 */
public class SingletonDemo01 {
    //1.0 创建实例对象
    private static SingletonDemo01 instance =null;//= new SingletonDemo01();
    private static SingletonDemo01 instance01 = new SingletonDemo01();



    //2.0 私有化构造函数
    private SingletonDemo01() {
    }

    //3.0 创建实例对象
    public static SingletonDemo01 getInstance() throws InterruptedException {
        if (instance == null) {
            Thread.sleep(10);
            instance  = new SingletonDemo01();
            return instance;
        }
        return instance;
    }

    public static SingletonDemo01 getInstance01() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return instance01;
    }


    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SingletonDemo01 instance = SingletonDemo01.getInstance01();
                    System.out.println(Thread.currentThread().getName()+":"+instance);
                }
            }).start();
        }


       /* for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SingletonDemo01 instance = null;
                    try {
                        instance = SingletonDemo01.getInstance();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName()+":"+instance);
                }
            }).start();
        }*/


    }
}
